package com.ray.ba.security.api.config.security;

import com.ray.ba.security.infra.mapper.SecUserMapper;
import com.ray.ba.security.infra.entity.SecUser;
import com.ray.ba.starter.security.jwt.security.JwtUser;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.util.ObjectUtils;

import java.util.HashSet;
import java.util.Set;

/**
 * CustomUserdetailservice
 *
 * @author ray
 * @date 2020/4/5
 */
public class CustomUserDetailsServiceImpl implements UserDetailsService {

    @Autowired
    SecUserMapper secUserMapper;

    @Override
    public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
        SecUser user = secUserMapper.selectOne(SecUser.builder().username(username).build());
        if(ObjectUtils.isEmpty(user)){
            throw new UsernameNotFoundException("User '" + username + "' not found");
        }

        // TODO: load real role
        Set<SimpleGrantedAuthority> grantedAuthorities = new HashSet<>();
        grantedAuthorities.add(new SimpleGrantedAuthority("admin"));
        return new JwtUser(user.getId(), user.getUsername(), user.getPassword(), user.getEmail(), grantedAuthorities);
    }

}

